# encoding:utf-8
"""
===============***===============
Auther : Hsir
Date   : 2022 - 11 - 23   17:47
File   : get_dbu_data.py
===============***===============
"""
import pytest
import requests
from autotest04.comms.dbutils import DBUtils
from autotest04.comms.pubilic_api import get_ini_data


# 封装用户登录case中从数据库摸取数据赋值给case
def get_zh_dbu_data(case):
    try:
        db = DBUtils()
        data = case["case_data"]
        db_user = db.find_one("select * from tb_user order by rand() limit 1")  # rand()函数，生成随机数，并且排序取一条（limit 1）可有可无
        if "#username#" in data.values():  # 如果#username#在case中就把上面的user_name赋值给case中的username
            data["username"] = db_user[1]  # 方法调用类的属性时必须存在
        if "#password#" in data.values():
            data["password"] = db_user[2]
    except Exception as e:
        print("封装数据库获取用户名和密码错误报错!", e)


# 封装用户登录case中从ini文件摸取数据赋值给case
def get_zh_ini_data(case):
    data = case["case_data"]
    try:
        username = get_ini_data("user", "name")
        password = get_ini_data("user", "password")
        if "#username#" in data.values():  # 如果#username#在case中就把上面的user_name赋值给case中的username
            data["username"] = username  # 方法调用类的属性时必须存在
        if "#password#" in data.values():
            data["password"] = password
    except Exception as e:
        print('ini文件获取账号信息失败!', e)


# 封装登录接口获取token鉴权
def get_token_data():
    try:
        response = requests.post(url="http://127.0.0.1:6666/business/token_login",
                                 data={"username": get_ini_data("user", "name"),
                                       "password": get_ini_data("user", "password"),
                                       "typeId": "101"})
        res = response.json()
        tk = res["token"]
        return tk
    except Exception as e:
        print("获取token鉴权失败!", e)


# 封装商品查询case中从数据库摸取商品信息数据赋值给case
def get_gs_dbu_data(case):
    try:
        db = DBUtils()
        data = case["case_data"]
        db_goodsid = db.find_one("select * from tb_goods order by rand() limit 1")
        if "#goodsId#" in data.values():
            data["goodsId"] = db_goodsid[0]
        if "#isOnSale#" in data.values():
            data["isOnSale"] = db_goodsid[11]
        if "#isPromote#" in data.values():
            data["isPromote"] = db_goodsid[12]
    except Exception as e:
        print("封装数据库获取商品信息报错!", e)


# 封装订单查询case中从数据库摸取订单信息数据赋值给case
def get_order_dbu_data(case):
    try:
        db = DBUtils()
        data = case["case_data"]
        db_order = db.find_one("select * from tb_order order by rand() limit 1")
        if "#orderId#" in data.values():
            data["orderId"] = db_order[0]
    except Exception as e:
        print("数据库获取订单信息报错!", e)



